package com.winterwar.web;

import java.awt.Color;
import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Set;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.spy.memcached.MemcachedClient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;
import com.winterwar.base.Convention;
import com.winterwar.base.Event;
import com.winterwar.base.RegisteredEvent;
import com.winterwar.base.Registration;
import com.winterwar.base.User;
import com.winterwar.base.WWAuthenticator;
import com.winterwar.base.WWComparators;
import com.winterwar.service.ConventionManager;
import com.winterwar.service.EventManager;
import com.winterwar.service.RegisteredEventManager;
import com.winterwar.service.RegistrationManager;
import com.winterwar.service.UserManager;

public class RegistrationAction extends DispatchAction{
	private static Log log = LogFactory.getLog(RegistrationAction.class);
	private RegistrationManager mgr;
	private UserManager userMgr;
	private EventManager eventMgr;
	private RegisteredEventManager regEventMgr;
	private ConventionManager conMgr;
	
	public void setConventionManager(ConventionManager mgr){
		this.conMgr = mgr;
	}
	
	public void setRegEventMgr(RegisteredEventManager mgr){
		this.regEventMgr = mgr;
	}
	
	public void setEventManager(EventManager mgr){
		this.eventMgr = mgr;
	}
	
	public void setUserManager(UserManager mgr){
		this.userMgr = mgr;
	}
	
	public void setManager(RegistrationManager mgr){
		this.mgr = mgr;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting delete...");
		}
		mgr.remove(request.getParameter("registration.registrationID"));
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("registration.deleted"));
		saveMessages(request, messages);
		return list(mapping, form, request, response);
	}

	@SuppressWarnings("unchecked")
	public ActionForward save(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting save...");
		}
		HttpSession session = request.getSession();
		User user = null;
		DynaActionForm registrationForm = (DynaActionForm) form;
		Registration registration = (Registration) registrationForm.get("registration");
		if(registrationForm.get("user") != null){
			user = (User) registrationForm.get("user");
		}
		if(user != null && user.getFirstName() != null && (registration.getUserID() == null || registration.getUserID().intValue() == 0)){
			user.setUsername(user.getFirstName().toLowerCase().substring(0,1) + user.getLastName().toLowerCase());
			user.setPassword("ww2009");
			user = userMgr.save(user);
			registration.setUserID(user.getUserID());
		}
		if(registration.getInsertDate() == null){
			registration.setInsertDate(new Date());
		}
		registration = mgr.save(registration);
		
		request.setAttribute("conID", registration.getConID().intValue() + "");
		
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("registration.saved"));
		saveMessages(request, messages);
		request.setAttribute("conID", request.getAttribute("conID"));
		
		if(registration.getStatus().intValue() == 3){
			log.info(registration.getRegID());
			sendEmail(registration.getRegID() + "");
		} else if(registration.getStatus().intValue() == 2){
			sendReviewEmail(registration.getRegID() + "");
		}
		return status(mapping, form, request, response);
	}

	public ActionForward status(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception{
		MemcachedClient cacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		String conID = (cacheClient.get("Curr_Con_ID") != null) ? cacheClient.get("Curr_Con_ID").toString() : null;;
		if(conID == null || conID.equals("")){
			conID = conMgr.getCurrentCon().getConID().toString();
			cacheClient.set("Curr_Con_ID", 86400, conID);
		}
		request.setAttribute("conID" , conID);
		request.setAttribute("registrations", mgr.getByConID(conID, ""));
		return mapping.findForward("status");
	}

	public ActionForward view(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse respone)
	throws Exception{
		String registrationID = (request.getAttribute("registrationID") == null) ? request.getParameter("registrationID") : request.getAttribute("registrationID").toString();
		String conID = (request.getAttribute("conID") == null) ? request.getParameter("conID") : request.getAttribute("conID").toString();

		if(conID != null && registrationID != null){
			request.setAttribute("registration", mgr.get(registrationID));
			request.setAttribute("con", conMgr.get(conID));
		}
		return mapping.findForward("view");
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting edit...");
		}
		DynaActionForm registrationForm = (DynaActionForm) form;
		String registrationID = (request.getAttribute("registrationID") == null) ? request.getParameter("registrationID") : request.getAttribute("registrationID").toString();
		String conID = (request.getAttribute("conID") == null) ? request.getParameter("conID") : request.getAttribute("conID").toString();

		request.setAttribute("conID", conID);
		request.setAttribute("users", userMgr.getAll());
		request.setAttribute("events", eventMgr.getByConID(conID, "3"));
		request.setAttribute("currentCon", conMgr.getCurrentCon());
		if(registrationID != null && registrationID.compareTo("") != 0){
			Registration registration = mgr.get(registrationID);
			request.setAttribute("registrationID", registrationID);
			if(registration == null){
				ActionMessages errors = new ActionMessages();
				errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("registration.missing"));
				saveErrors(request, errors);
				
				return mapping.findForward("list");
			}
			request.setAttribute("regEvents", registration.getEvents());
			if(registration.getUserID() != null && registration.getUserID().intValue() != 0){
				User user = userMgr.get(registration.getUserID().toString());
				request.setAttribute("user", user);
				request.setAttribute("userID", user.getUserID());
			}
			registrationForm.set("registration", registration);
		} else {
			if(request.getParameter("userID") != null && request.getParameter("userID").compareTo("")!=0 && request.getParameter("userID").compareTo("null")!=0){
				User user = userMgr.get(request.getParameter("userID"));
				for(Registration userReg : user.getRegistrations()){
					if(conID.compareTo(userReg.getConID().toString())== 0){
						request.setAttribute("regExist", true);
						break;
					}
				}
				request.setAttribute("user", user);
				request.setAttribute("userID", user.getUserID());
			} else {
				request.setAttribute("userID", "0");
			}
			Registration reg = new Registration();
			reg.setType(2);
			registrationForm.set("registration", reg);
		}
		return mapping.findForward("edit");
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
						HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		request.setAttribute("registrations", mgr.getAll());
		
		return mapping.findForward("list");
	}

	public ActionForward listByConID(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		MemcachedClient cacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		String conID = request.getParameter("conID");
		String status = request.getParameter("status");
		if(conID == null || conID.equals("")){
			conID = (cacheClient.get("Curr_Con_ID") != null) ? cacheClient.get("Curr_Con_ID").toString() : null;;
			if(conID == null || conID.equals("")){
				conID = conMgr.getCurrentCon().getConID().toString();
			}
		}
		request.setAttribute("registrations", mgr.getByConID(conID, status));
		request.setAttribute("conID", conID + "");
		return mapping.findForward("list");
	}

	public ActionForward register(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting save...");
		}
		HttpSession session = request.getSession();
		DynaActionForm registrationForm = (DynaActionForm) form;
		ActionMessages errors = form.validate(mapping, request);
		
		int eventCount=0;
		int judging = 0;
		Convention currCon = conMgr.getCurrentCon();

		if(errors != null && !errors.isEmpty()){
			saveErrors(request, errors);
			return edit(mapping, form, request, response);
		}
		Registration registration = (Registration) registrationForm.get("registration");
		if(session.getAttribute("randFormID").toString().equals(request.getParameter("formID").toString())){
			Random gen = new Random(new Date().getTime());
			session.setAttribute("randFormID", gen.nextInt() + "");

			if(registration.getInsertDate() == null){
				registration.setInsertDate(new Date());
			}
			registration = mgr.save(registration);
			String[] eventIDs = request.getParameterValues("events");
			if(eventIDs != null){
				for(int i=0;i<eventIDs.length;i++){
					if(!eventIDs[i].equals("0")){
						RegisteredEvent regEvent = new RegisteredEvent();
						regEvent.setEventID(Integer.valueOf(eventIDs[i]));
						regEvent.setRegID(registration.getRegID());
						regEvent.setUserID(registration.getUserID());
						regEvent.setConID(registration.getConID());
						regEvent.setStatus(1);
						regEventMgr.save(regEvent);
						eventCount++;
					}
				}
			}

			@SuppressWarnings("unchecked")
			List<Event> events = eventMgr.getByConID(registration.getConID().toString(), "3");
			for(Event e : events){
				if(e.getUserID().intValue() == registration.getUserID().intValue())
					judging++;
			}
			
			switch(registration.getType()){
			case 1:
				registration.setCost(currCon.getSingleDayCost());
				if(judging == 1) registration.setCostOffset(currCon.getSingleDayCost()/2);
				if(judging >= 2) registration.setCostOffset(currCon.getSingleDayCost());
				break;
			case 2:
				registration.setCost(currCon.getWeekendPassCost());
				if(judging == 1) registration.setCostOffset(currCon.getWeekendPassCost()/2);
				if(judging >= 2) registration.setCostOffset(currCon.getWeekendPassCost());
				break;
			case 3:
				registration.setCost(currCon.getWeekendASLCost());
				if(judging == 1) registration.setCostOffset(currCon.getWeekendASLCost()/2);
				if(judging >= 2) registration.setCostOffset(currCon.getWeekendASLCost());
				break;
			}
			registration.setCost(registration.getCost() + (currCon.getDefaultEventCost() * eventCount));
			registration.setPaid(0.0);
		
			mgr.save(registration);
			
			request.setAttribute("conID", registration.getConID().intValue() + "");
			
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("registration.saved"));
			saveMessages(request, messages);
			request.setAttribute("conID", request.getAttribute("conID"));
			request.setAttribute("registration", mgr.get(registration.getRegID().toString()));
		}
		return mapping.findForward("success");
	}

	public ActionForward confirm(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting save...");
		}
		HttpSession session = request.getSession();
		DynaActionForm registrationForm = (DynaActionForm) form;
		ActionMessages errors = form.validate(mapping, request);
		
		int eventCount=0;
		int judging = 0;
		Convention currCon = conMgr.getCurrentCon();

		if(errors != null && !errors.isEmpty()){
			saveErrors(request, errors);
			return edit(mapping, form, request, response);
		}
		Registration registration = (Registration) registrationForm.get("registration");
		if(session.getAttribute("randFormID").toString().equals(request.getParameter("formID").toString())){
			Random gen = new Random(new Date().getTime());
			session.setAttribute("randFormID", gen.nextInt() + "");

			if(registration.getInsertDate() == null){
				registration.setInsertDate(new Date());
			}

			String[] eventIDs = request.getParameterValues("events");
			Set<Event> regEvents = new HashSet<Event>();
			if(eventIDs != null){
				for(int i=0;i<eventIDs.length;i++){
					if(!eventIDs[i].equals("0")){
						Event e = eventMgr.get(eventIDs[i]);
						regEvents.add(e);
						eventCount++;
					}
				}
			}
			User user = userMgr.get(registration.getUserID().toString());
			@SuppressWarnings("unchecked")
			List<Event> events = eventMgr.getByConID(registration.getConID().toString(), "3");
			for(Event e : events){
				if(e.getUserID().intValue() == registration.getUserID().intValue())
					judging++;
			}

			switch(registration.getType()){
			case 1:
				registration.setCost(currCon.getSingleDayCost());
				if(judging == 1) registration.setCostOffset(currCon.getSingleDayCost()/2);
				if(judging >= 2) registration.setCostOffset(currCon.getSingleDayCost());
				break;
			case 2:
				registration.setCost(currCon.getWeekendPassCost());
				if(judging == 1) registration.setCostOffset(currCon.getWeekendPassCost()/2);
				if(judging >= 2) registration.setCostOffset(currCon.getWeekendPassCost());
				break;
			case 3:
				registration.setCost(currCon.getWeekendASLCost());
				if(judging == 1) registration.setCostOffset(currCon.getWeekendASLCost()/2);
				if(judging >= 2) registration.setCostOffset(currCon.getWeekendASLCost());
				break;
			}
			registration.setCost(registration.getCost() + (currCon.getDefaultEventCost() * eventCount));
			registration.setPaid(0.0);
			
			request.setAttribute("conID", registration.getConID().intValue() + "");
			request.setAttribute("events", regEvents);
			request.setAttribute("registration", registration);
			request.setAttribute("user", user);
			registrationForm.set("registration", registration);
		}
		return mapping.findForward("confirm");
	}

	@SuppressWarnings("unchecked")
	public ActionForward registrationReportSheet(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		Paragraph paragraph;
		String conID = request.getParameter("conID");
		String status = request.getParameter("status");
		List<Registration> registrations = mgr.getByConID(conID, status);
		NumberFormat nf = NumberFormat.getCurrencyInstance();
		Registration[] regs = new Registration[registrations.size()];

		int j=0;
		for(Registration reg: registrations){
			regs[j] = reg;
			j++;
		}
		Arrays.sort(regs, new WWComparators.RegistrationComparator());

		String path = getServlet().getServletContext().getRealPath("/wwadmin/reports/");

		Document report = new Document(PageSize.LETTER, 36, 36, 36, 36);
		PdfWriter.getInstance(report, new FileOutputStream(path + "/RegDesk.pdf"));
		report.open();
		Font[] fonts = { new Font(Font.TIMES_ROMAN, 24, Font.BOLD),
						new Font(Font.TIMES_ROMAN, 12, Font.NORMAL),
						new Font(Font.TIMES_ROMAN, 14, Font.BOLD)};
		for(Registration reg:regs){
			paragraph = new Paragraph();
			paragraph.setKeepTogether(true);
			paragraph.add(new Paragraph(reg.getUser().getLastName() + ", " + reg.getUser().getFirstName(),fonts[0]));
			//report.add(new Paragraph("\n"));
			paragraph.add(new Paragraph(reg.getUser().getAddress1(), fonts[1]));
			paragraph.add(new Paragraph(reg.getUser().getCity() + ", " + reg.getUser().getState() + "  " + reg.getUser().getZipCode(), fonts[1]));
			switch(reg.getType()){
			case 1:
				if(reg.getDayRegistered() == 1)
					paragraph.add(new Paragraph("Registration Type: Friday Only", fonts[1] ));
				if(reg.getDayRegistered() == 2)
					paragraph.add(new Paragraph("Registration Type: Saturday Only", fonts[1] ));
				if(reg.getDayRegistered() == 3)
					paragraph.add(new Paragraph("Registration Type: Sunday Only", fonts[1] ));
				break;
			case 2:
				paragraph.add(new Paragraph("Registration Type: Weekend", fonts[1] ));
				break;
			case 3:
				paragraph.add(new Paragraph("Registration Type: ASL Weekend", fonts[1] ));
				break;
			}
			paragraph.add(new Paragraph("Total Amount: " + nf.format(reg.getCost()),fonts[1]));
			paragraph.add(new Paragraph("Discount : " + nf.format(reg.getCostOffset()), fonts[1]));
			paragraph.add(new Paragraph("Sub-Total : " + nf.format((reg.getCost() - reg.getCostOffset())), fonts[1]));
			paragraph.add(new Paragraph("Amount Paid : " + nf.format(reg.getPaid()), fonts[1]));
			paragraph.add(new Paragraph("Amount Owed : " + nf.format((reg.getCost() - reg.getCostOffset() - reg.getPaid())), fonts[2]));
			paragraph.add(Chunk.NEWLINE);
			Set<RegisteredEvent> rawEvents = reg.getEvents();
			RegisteredEvent[] events = new RegisteredEvent[rawEvents.size()];
			if(rawEvents != null){
				int i=0;
				for(RegisteredEvent e:rawEvents){
					events[i] = e;
					i++;
				}
				Arrays.sort(events, new WWComparators.EventSlotComparator());
			}
			paragraph.add(Chunk.NEWLINE);
			paragraph.add(new Paragraph("Events :", fonts[2]));
			if(events != null){
				for(RegisteredEvent e: events){
					paragraph.add(new Paragraph(e.getEvent().getSlotName() + " : " + e.getEvent().getEventName(), fonts[1]));
				}
			}
			report.add(paragraph);
			report.add(new Chunk(new LineSeparator(1, 80, Color.BLACK, Element.ALIGN_LEFT, -2)));
		}
		report.close();
		
		return status(mapping, form, request, response);
	}

	@SuppressWarnings("unchecked")
	public ActionForward registrationCheatSheet(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		Paragraph paragraph;
		String conID = request.getParameter("conID");
		String status = request.getParameter("status");
		List<Registration> registrations = mgr.getByConID(conID, status);
		Registration[] regs = new Registration[registrations.size()];

		int j=0;
		for(Registration reg: registrations){
			regs[j] = reg;
			j++;
		}
		Arrays.sort(regs, new WWComparators.RegistrationComparator());
	
		String path = getServlet().getServletContext().getRealPath("/wwadmin/reports/");

		Document report = new Document(PageSize.LETTER, 36, 36, 36, 36);
		PdfWriter.getInstance(report, new FileOutputStream(path + "/RegCheat.pdf"));
		report.open();
		Font[] fonts = { new Font(Font.TIMES_ROMAN, 24, Font.BOLD),
						new Font(Font.TIMES_ROMAN, 12, Font.NORMAL),
						new Font(Font.TIMES_ROMAN, 14, Font.BOLD)};
		
		for(Registration reg:regs){
			paragraph = new Paragraph();
			paragraph.setKeepTogether(true);
			paragraph.add(new Chunk(reg.getUser().getLastName() + ", " + reg.getUser().getFirstName() + "\n",fonts[0]));
			Set<RegisteredEvent> rawEvents = reg.getEvents();
			RegisteredEvent[] events = new RegisteredEvent[rawEvents.size()];
			if(rawEvents != null){
				int i=0;
				for(RegisteredEvent e:rawEvents){
					events[i] = e;
					i++;
				}
				Arrays.sort(events, new WWComparators.EventSlotComparator());
			}
			paragraph.add(new Chunk("Events :\n", fonts[2]));
			if(events != null){
				for(RegisteredEvent e: events){
					paragraph.add(new Chunk(e.getEvent().getSlotName() + " : " + e.getEvent().getEventName() + "\n", fonts[1]));
				}
			}
			paragraph.add(new Chunk("--------------------------------------------------\n\n"));
			report.add(paragraph);
		}
		report.close();
		
		return status(mapping, form, request, response);
	}

	@SuppressWarnings("unchecked")
	public ActionForward eventSignUpSheets(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		String conID = request.getParameter("conID");
		String status = request.getParameter("status");
		List<Event> rawEvents = eventMgr.getByConID(conID, status);
		Event[] events = new Event[rawEvents.size()];
		int j=0;
		for(Event e: rawEvents){
			events[j] = e;
			j++;
		}
		Arrays.sort(events, new WWComparators.RealEventSlotComparator());
		List<Registration> regs = mgr.getByConID(conID, status);

		String path = getServlet().getServletContext().getRealPath("/wwadmin/reports/");

		Document report = new Document(PageSize.LETTER, 36, 36, 36, 36);
		PdfWriter.getInstance(report, new FileOutputStream(path + "/SignupSheets.pdf"));
		report.open();
		Font[] fonts = { new Font(Font.TIMES_ROMAN, 24, Font.BOLD),
						new Font(Font.TIMES_ROMAN, 12, Font.NORMAL),
						new Font(Font.TIMES_ROMAN, 10, Font.NORMAL)};
		for(Event event:events){
			report.add(new Paragraph(event.getSlotName() + "  --  Table Number " + event.getTableName() + "\n" + event.getEventName()));
			report.add(new Paragraph("Judge: " + event.getUser().getFirstName() + " " + event.getUser().getLastName() + " -- " + event.getTotalSeats() + " Seats.",fonts[1]));
			int i = 0;
			if(event.getTotalSeats().intValue() >= 40){
				PdfPTable table = new PdfPTable(2);
				table.setWidthPercentage(100);
				for(Registration reg:regs){
					for(Object o : reg.getEvents()){
						RegisteredEvent e = (RegisteredEvent) o;
						if(e.getEventID().intValue() == event.getEventID().intValue()){
							PdfPCell cell = new PdfPCell(new Paragraph((i+1) + ")  " + reg.getUser().getFirstName() + " " + reg.getUser().getLastName(),fonts[1]));
							cell.setBorderWidth(0);
							table.addCell(cell);
							i++;
							break;
						}
					}
				}
				while(i<event.getTotalSeats().intValue()){
					PdfPCell cell = new PdfPCell(new Paragraph((i+1) + ")  " + "______________________________________",fonts[1]));
					cell.setBorderWidth(0);
					table.addCell(cell);
					i++;
				}
				report.add(table);
			} else {
				for(Registration reg:regs){
					for(Object o : reg.getEvents()){
						RegisteredEvent e = (RegisteredEvent) o;
						if(e.getEventID().intValue() == event.getEventID().intValue()){
							report.add(new Paragraph((i+1) + ")  " + reg.getUser().getFirstName() + " " + reg.getUser().getLastName(),fonts[2]));
							i++;
							break;
						}
					}
				}
				while(i<event.getTotalSeats().intValue()){
					report.add(new Paragraph((i+1) + ")  " + "___________________________________________",fonts[2]));
					i++;
				}
			}
			report.newPage();
		}
		report.close();
		
		return status(mapping, form, request, response);
	}
	public void sendEmail(String registrationID)
	throws Exception{
		if(log.isDebugEnabled()){
			log.info("Starting send mail...");
		}
		Registration reg = mgr.get(registrationID);
		User usr = userMgr.get(reg.getUserID() + "");
		List<RegisteredEvent> regedEvents = regEventMgr.getByRegistration(registrationID); 

		StringBuilder eMailBody = new StringBuilder();
		try{
			DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            java.util.Date date = new java.util.Date();

			eMailBody.append("Hi "+usr.getFirstName()+",\n\r");
			eMailBody.append("You registered for the following event(s) at Winter War on " + dateFormat.format(date) + " :\n\r");
			
			//for(int i=0; i< reg.getEvents().size();i++ );
			for(RegisteredEvent e : regedEvents){
				Event evnt = eventMgr.get(e.getEventID() + "");
				eMailBody.append(evnt.getSlotName() + " -- " + evnt.getEventName() + "\n\r");
			}
			
			eMailBody.append("You paid "+NumberFormat.getCurrencyInstance().format(reg.getPaid())+" and owe "+NumberFormat.getCurrencyInstance().format(reg.getCost() - reg.getPaid() - reg.getCostOffset())+".  You can resolve the difference at the desk when you arrive.\n\r");
			eMailBody.append("If you have any changes or questions, please email or call me at 217-778-3016.\n\r\n\r");
			
			eMailBody.append("See you at the con\n\r,");
			eMailBody.append("Susan McKinney\n\r");
			eMailBody.append("Convention Registrar");
	
			Properties props = new Properties();
			props.put("mail.smtp.host", "winterwar.org");
		    props.put("mail.smtp.auth", "true");
		    props.put("mail.smtp.user", "registrar@mail.winterwar.org");
		    props.put("mail.smtp.pass", "Battle0n"); 	
			//Get the default Session
			Session mailSession = Session.getDefaultInstance(props, new WWAuthenticator());
			
			// create a message
			Message msg = new MimeMessage(mailSession);
			
			// set the from and to address
			InternetAddress addressFrom = new InternetAddress("smckin@gmail.com");
			msg.setFrom(addressFrom);
			InternetAddress[] addressTo = new InternetAddress[2]; 
						
			
		    addressTo[0] = new InternetAddress(usr.getEmail());
		    addressTo[1] = new InternetAddress("smckin@gmail.com");

			msg.setRecipients(Message.RecipientType.TO, addressTo);
			
			
			//You can also set your custom headers in the Email if you Want
			msg.addHeader("MyHeaderName", "myHeaderValue");
			
			// Setting the Subject and Content Type
			msg.setSubject("Winter War Convention Account Information");
			msg.setContent(eMailBody.toString(), "text/plain");
			Transport.send(msg);
				
		} catch(Exception ex){
			log.error(ex);
			for(StackTraceElement element : ex.getStackTrace())
				log.error(element.toString());
		}
	}
/*Hi <name>,
You registered for the following event(s) at Winter War on <date>:

list events

The following events are filled, please email me alternate choices. You paid $.... and owe $x.  You can resolve the difference at the desk when you arrive.
If you have any changes or questions, please email or call me at 217-778-3016.

See you at the con,
Susan McKinney
Convention Registrar*/
	public void sendReviewEmail(String registrationID)
	throws Exception{
		if(log.isDebugEnabled()){
			log.info("Starting send mail...");
		}
		Registration reg = mgr.get(registrationID);
		User usr = userMgr.get(reg.getUserID() + "");
	
		StringBuilder eMailBody = new StringBuilder();
		try{
			double toPay = reg.getCost() - reg.getCostOffset() - reg.getPaid();
			toPay = toPay + .31;
			toPay = toPay / 0.971;
			toPay = toPay * 100;
			toPay = Math.round(toPay);
			toPay = toPay/100;
	
			
	        eMailBody.append("Dear " + usr.getFirstName() + ",\n\r\n\r");
			eMailBody.append("\tWe have received your pre-registration for Winter War.  You owe " + NumberFormat.getCurrencyInstance().format(reg.getCost() - reg.getPaid() - reg.getCostOffset()) + " by check or " + NumberFormat.getCurrencyInstance().format(toPay) + " by paypal to smckin@gmail.com. Until we receive payment you are not officially registered. If you have any questions please email me at the above address or call at 217-778-3016 to make arrangements.  If you need to make changes to your pre-reg please contact me and I will assist you in making those changes.\n\r\n\r");
			eMailBody.append("Thanks,\n\r");
			eMailBody.append("Susan McKinney");
			
			Properties props = new Properties();
			props.put("mail.smtp.host", "winterwar.org");
		    props.put("mail.smtp.auth", "true");
		    props.put("mail.smtp.user", "registrar@mail.winterwar.org");
		    props.put("mail.smtp.pass", "Battle0n"); 	
			//Get the default Session
			Session mailSession = Session.getDefaultInstance(props, new WWAuthenticator());
			
			// create a message
			Message msg = new MimeMessage(mailSession);
			
			// set the from and to address
			InternetAddress addressFrom = new InternetAddress("smckin@gmail.com");
			msg.setFrom(addressFrom);
			InternetAddress[] addressTo = new InternetAddress[1]; 
						
			
		    addressTo[0] = new InternetAddress(usr.getEmail());
	
			msg.setRecipients(Message.RecipientType.TO, addressTo);
			
			
			//You can also set your custom headers in the Email if you Want
			msg.addHeader("MyHeaderName", "myHeaderValue");
			
			// Setting the Subject and Content Type
			msg.setSubject("Winter War Convention Account Information");
			msg.setContent(eMailBody.toString(), "text/plain");
			Transport.send(msg);
				
		} catch(Exception ex){
			log.error(ex);
			for(StackTraceElement element : ex.getStackTrace())
				log.error(element.toString());
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward registrationPaymentsOwed(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		Paragraph paragraph;
		String conID = request.getParameter("conID");
		String status = request.getParameter("status");
		List<Registration> registrations = mgr.getByConID(conID, status);
		Registration[] regs = new Registration[registrations.size()];

		int j=0;
		for(Registration reg: registrations){
			regs[j] = reg;
			j++;
		}
		Arrays.sort(regs, new WWComparators.RegistrationComparator());
	
		String path = getServlet().getServletContext().getRealPath("/wwadmin/reports/");

		Document report = new Document(PageSize.LETTER, 36, 36, 36, 36);
		PdfWriter.getInstance(report, new FileOutputStream(path + "/OweReport.pdf"));
		report.open();
		Font[] fonts = { new Font(Font.TIMES_ROMAN, 24, Font.BOLD),
						new Font(Font.TIMES_ROMAN, 12, Font.NORMAL)};
		
		paragraph = new Paragraph();
		paragraph.add(new Chunk("People Owing Money.", fonts[0]));
		report.add(paragraph);
		for(Registration reg:regs){
			if(reg.getCost().doubleValue() - reg.getPaid().doubleValue() - reg.getCostOffset().doubleValue() > 0.0){
				paragraph = new Paragraph();
				paragraph.setKeepTogether(true);
				paragraph.add(new Chunk(reg.getUser().getLastName() + ", " + reg.getUser().getFirstName() + ": " + (reg.getCost().doubleValue() - reg.getPaid().doubleValue() - reg.getCostOffset().doubleValue()) +"\n",fonts[1]));
				report.add(paragraph);
			}
		}
		
		paragraph = new Paragraph();
		paragraph.add(new Chunk("--------------------------------------------------\n\n"));
		report.add(paragraph);
		
		paragraph = new Paragraph();
		paragraph.add(new Chunk("People We Owe.", fonts[0]));
		report.add(paragraph);
		for(Registration reg:regs){
			if(reg.getCost().doubleValue() - reg.getPaid().doubleValue() - reg.getCostOffset().doubleValue() < 0.0){
				paragraph = new Paragraph();
				paragraph.setKeepTogether(true);
				paragraph.add(new Chunk(reg.getUser().getLastName() + ", " + reg.getUser().getFirstName() + ": " + (reg.getCost().doubleValue() - reg.getPaid().doubleValue() - reg.getCostOffset().doubleValue()) +"\n",fonts[1]));
				report.add(paragraph);
			}
		}
		report.close();
		
		return status(mapping, form, request, response);
	}
}
